import SpawnController from '@/modules/structures/spawn'
import { RemoteHarvestTask } from './types'
import { CreepRoles } from '@/modules/structures/spawn/types'
import { goTo } from '@/modules/move'
import { isInterval } from '@/ayaka'

/**
 * 孵化预定者
 */
export const spawnRemoteReserver = function (room: MyRoom, task: RemoteHarvestTask) {
    if (!isInterval(11) || room.energyCapacityAvailable < 650) return

    let reserverNumber = task.data.controllerFreePos && 1
    if (task.data.controllerFreePos > 1 && room.energyCapacityAvailable < 1300) {
        reserverNumber = 2
    }

    if (task.remoteReserver.length >= reserverNumber) return

    if (SpawnController.searchSpawnTaskByRole(room, CreepRoles.remoteReserver).length) return

    const partNumber = Math.min(Math.floor(room.energyCapacityAvailable / 650), 4)
    if (!partNumber) return

    const creepName = SpawnController.addSpawnTask(room, {
        role: CreepRoles.remoteReserver,
        body: [
            [CLAIM, partNumber],
            [MOVE, partNumber],
        ],
    })
    if (!creepName) return

    task.remoteReserver.push(creepName)
}

/**
 * 预定者工作
 */
export const remoteReserverWork = function (creeps: Creep[], task: RemoteHarvestTask, remoteRoom?: Room) {
    creeps = creeps.filter((creep) => !creep.spawning)

    creeps.forEach((creep) => {
        delete creep.memory.stand

        if (!remoteRoom) {
            goTo(creep, new RoomPosition(25, 25, task.roomName), { range: 23 })
            return
        }

        const controller = remoteRoom.controller!

        if (!creep.pos.isNearTo(controller)) {
            goTo(creep, controller.pos, { range: 1 })
            return
        }

        creep.memory.stand = true
        if (!creep.memory.ready) {
            if (!controller.sign || ![creep.owner.username, 'Screeps'].includes(controller.sign.username)) {
                creep.signController(controller, `Claimed by ${creep.owner.username}, please stay away!`)
            }
            creep.memory.ready = true
        }
        if (controller.reservation && controller.reservation.username !== creep.owner.username) {
            creep.attackController(controller)
            return
        }
        if (controller.owner && controller.owner.username !== creep.owner.username) {
            creep.attackController(controller)
            return
        }
        creep.reserveController(controller)
    })
}
